import json
import random
import re
from django.views import View
from django.http import HttpResponse,JsonResponse
from django_redis import get_redis_connection

from celery_tasks.sms.tasks import ccp_send_sms_code
import logging

from libs.captcha.captcha import captcha

logger = logging.getLogger('django')


class ImageCodeView(View):
    """ 图形验证码"""
    def get(self, request):
        cur = request.GET.get('cur')
        pre = request.GET.get('pre')
        if not cur:
            return JsonResponse({'errno': 400, 'errmsg': '缺少参数'})
        if not re.match('[\w]+', cur):
            return JsonResponse({'errno': 400, 'errmsg': 'cur格式有误'})
        if pre:
            if not re.match('[\w]+', pre):
                return JsonResponse({'errno': 400, 'errmsg': 'pre格式有误'})

        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_code')
        try:
            redis_conn.setex('image_code_%s' % cur, 300, text)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 400, 'errmsg': 'redis写入错误'})
        return HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):
    """ 短信验证码"""
    def post(self, request):
        redis_conn = get_redis_connection('verify_code')
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        cur = json_dict.get('id')
        text = json_dict.get('text')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return JsonResponse({'errno': 400, 'errmsg': '短信发送过于频繁'})

        if not all([mobile, cur, text]):
            return JsonResponse({'errno': 400, 'errmsg': '缺少必传参数'})

        image_code_server = redis_conn.get('image_code_%s' % cur)
        if image_code_server is None:
            return JsonResponse({'errno': 400, 'errmsg': '图形验证码失效'})
        try:
            redis_conn.delete('image_code_%s' % cur)
        except Exception as e:
            logger.error(e)
        image_code_server = image_code_server.decode()
        if text.lower() != image_code_server.lower():
            return JsonResponse({'errno': 400, 'errmsg': '输入的图形验证码有误'})
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        print(sms_code)
        pl = redis_conn.pipeline()
        pl.setex('sms_code_%s' % mobile, 300, sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.execute()
        # ccp_send_sms_code.delay(mobile, sms_code)
        return JsonResponse({'errno': 0, 'errmsg': '发送短信成功'})